package com.zhuiyun.project.api.sysUser.service.impl;

import com.zhuiyun.project.api.recording.entiy.TransactionHistory;
import com.zhuiyun.project.api.recording.mapper.TransactionHistoryMapper;
import com.zhuiyun.project.api.recording.model.TransactionHistoryModel;
import com.zhuiyun.project.api.sysUser.entiy.SysUser;
import com.zhuiyun.project.api.sysUser.mapper.SysUserMapper;
import com.zhuiyun.project.api.sysUser.model.SysUserModel;
import com.zhuiyun.project.api.sysUser.service.SysUserService;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.util.BeanUtils;
import com.zhuiyun.project.util.ObjectUtils;
import com.zhuiyun.project.util.RedisUtil;

import com.zhuiyun.project.util.UserUtils;
import com.zhuiyun.project.util.constants.CommonConstants;
import com.zhuiyun.project.util.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.util.pageUtil.PageRequest;
import com.zhuiyun.project.util.pageUtil.PageResult;
import com.zhuiyun.project.util.validator.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SysUserServiceImpl
 * @Description 用户管理服务类 用于实现用户的增删改查 登录 注销
 * @Author zcy
 * @Date 2023/3/24 16:15
 **/
@Service()
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    TransactionHistoryMapper transactionHistoryMapper;
    /**
     * 通过登录名获取用户信息
     * @param loginName
     * @return
     */
    @Override
    public SysUser getUserByLoginName(String loginName) {
        // 判断用户登录名是否为空
        if(ObjectUtils.isNotEmpty(loginName)){
            // 使用Example表达式查询登录人信息
            Example example = new Example(SysUser.class);
            example.createCriteria().andEqualTo("loginName",loginName);
            return sysUserMapper.selectOneByExample(example);
        }else{
            return null;
        }
    }
    /**
     * 通过邮箱查询用户
     * @param emailAccount
     * @return
     */
    @Override
    public SysUser getUserByEmailAccount(String emailAccount) {
        // 判断用户登录名是否为空
        if(ObjectUtils.isNotEmpty(emailAccount)){
            // 使用Example表达式查询登录人信息
            Example example = new Example(SysUser.class);
            example.createCriteria().andEqualTo("email",emailAccount);
            return sysUserMapper.selectOneByExample(example);
        }else{
            return null;
        }
    }

    /**
     * 更新登录成功后更新用户信息
     * @param sysUser
     */
    @Override
    public void updateUserByLogin(SysUser sysUser) {
        if(ObjectUtils.isNotEmpty(sysUser)&&ObjectUtils.isNotEmpty(sysUser.getId())){
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
        }
    }
    /**
     *
     * 新增用户
     * @param sysUserModel
     * @return
     * @throws CommonException
     */
    @Override
    public CommonResult saveUser(SysUserModel sysUserModel) throws CommonException {
        // 验证参数的规范性
        if(ValidatorUtil.ValidationObject(sysUserModel)){
            SysUser sysUser = new SysUser();
            // sysUserModel 对象拷贝成 sysUser
            BeanUtils.copy(sysUserModel, sysUser);
            BigDecimal zero = new BigDecimal(0.00);
            sysUser.setAmount(zero);
            sysUser.setIs_del(0);
            // 设置密码
            sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
            int i = sysUserMapper.insert(sysUser);
            if(i>0){
                return CommonResult.ok(EmErrorCode.SAVE_OK);
            }else{
                return CommonResult.ok(EmErrorCode.SAVE_ERROR);
            }
        }else{
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }
    }

    /**
     * 修改用户信息
     * @param sysUserModel
     * @return
     */
    @Override
    public CommonResult updateUser(SysUserModel sysUserModel) throws CommonException {
        // 验证参数的规范性
        if(ValidatorUtil.ValidationObject(sysUserModel)){
            SysUser sysUser = new SysUser();
            // sysUserModel 对象拷贝成 sysUser
            BeanUtils.copy(sysUserModel, sysUser);
            if(ObjectUtils.isNotEmpty(sysUserModel.getNewPassword())){
                sysUser.setPassword(bCryptPasswordEncoder.encode(sysUserModel.getNewPassword()));
            }
            int i = sysUserMapper.updateByPrimaryKeySelective(sysUser);
            if(i>0){
                return CommonResult.ok(EmErrorCode.UPDATE_OK);
            }else{
                return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
            }
        }else{
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @Override
    public CommonResult delUserById(Integer id) throws CommonException {
        // 判断是否id为空
        if(ObjectUtils.isNotEmpty(id)){
            SysUser sysUser = new SysUser();
            sysUser.setId(id);
            sysUser.setIs_del(1);
            int i = sysUserMapper.updateByPrimaryKeySelective(sysUser);
            // 判断是否操作成功
            if(i>0){
                return CommonResult.ok(EmErrorCode.DELETE_OK);
            }else{
                return CommonResult.ok(EmErrorCode.DELETE_ERROR);
            }
        }else{
            throw new CommonException(EmErrorCode.ID_NULL);
        }
    }

    /**
     * 分页查询
     * @param sysUserModel
     * @param pageRequest
     * @return
     */
    @Override
    public CommonResult getUserByPage(SysUserModel sysUserModel, PageRequest pageRequest) {
        // 设置分页
        MybatisPageHelper.startPage(pageRequest);
        Example example = new Example(SysUser.class);
        // 设置模糊查询
        if(ObjectUtils.isNotEmpty(sysUserModel.getUserName())){
            example.createCriteria().andLike("userName","%"+sysUserModel.getUserName()+"%");
        }
        PageResult pageResult = MybatisPageHelper.getPageResult(sysUserMapper.selectByExample(example));
        return CommonResult.ok(pageResult);
    }

    /**
     * 根据手机号查询用户信息
     * @param phone
     * @return
     */
    @Override
    public SysUser getUserByPhoneAccount(String phone) {
        // 判断用户登录名是否为空
        if(ObjectUtils.isNotEmpty(phone)){
            // 使用Example表达式查询登录人信息
            Example example = new Example(SysUser.class);
            example.createCriteria().andEqualTo("phone",phone);
            return sysUserMapper.selectOneByExample(example);
        }else{
            return null;
        }
    }

    /**
     * 根据手机号查询用户信息
     * @param userName
     * @return
     */
    public SysUser getUserByUserName(String userName) {
        // 判断用户登录名是否为空
        if(ObjectUtils.isNotEmpty(userName)){
            // 使用Example表达式查询登录人信息
            Example example = new Example(SysUser.class);
            example.createCriteria().andEqualTo("userName",userName);
            return sysUserMapper.selectOneByExample(example);
        }else{
            return null;
        }
    }
    /**
     * 添加用户
     * @param sysUserModel
     * @return
     * @throws CommonException
     */
    @Override
    public CommonResult registerUser(SysUserModel sysUserModel) throws CommonException {
        // 首先验证验证码是否正确
        String key = CommonConstants.CACHE_PHONE_CODE+sysUserModel.getPhone()+sysUserModel.getCaptcha();
        Object o = RedisUtil.get(key);
        if(!ObjectUtils.isNotEmpty(o)){
            throw new CommonException(EmErrorCode.CODE_IS_ERROR);
        }
        SysUser userByUserName = getUserByUserName(sysUserModel.getUserName());
        if(ObjectUtils.isNotEmpty(userByUserName)){
            throw new CommonException(EmErrorCode.USERNAME_EXIST);
        }
        // 验证参数的规范性
        if(ValidatorUtil.ValidationObject(sysUserModel)){
            SysUser sysUser = new SysUser();
            // sysUserModel 对象拷贝成 sysUser
            BeanUtils.copy(sysUserModel, sysUser);
            // 设置密码
            sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
            BigDecimal bigDecimal = new BigDecimal(0.00);
            sysUser.setIs_del(0);
            sysUser.setAmount(bigDecimal);
            SysUser userByPhoneAccount = getUserByPhoneAccount(sysUser.getPhone());
            if (userByPhoneAccount != null) {
                return CommonResult.error(EmErrorCode.SAVE_ERROR);
            }else {
                int i = sysUserMapper.insert(sysUser);
                if(i>0){
                    return CommonResult.ok(EmErrorCode.SAVE_OK);
                }else{
                    return CommonResult.ok(EmErrorCode.SAVE_ERROR);
                }
            }
        }
        else{
            return CommonResult.error(EmErrorCode.SAVE_ERROR);
        }
    }

    /*
    * @Author 李中博
    * @Description 金币充值
    * @Date 2024/9/24 11:32
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param sysUserModel
    */
    @Override
    @Transactional
    public  CommonResult amountPay(SysUserModel sysUserModel) throws CommonException{
        try {
            // 验证参数的规范性
            if(ObjectUtils.isNotEmpty(sysUserModel.getAmount())&&ObjectUtils.isNotEmpty(sysUserModel.getPhone())){
                //充值记录
                TransactionHistory transactionHistory=new TransactionHistory();
                transactionHistory.setCreateTime(sysUserModel.getUpdateTime());
                transactionHistory.setState(CommonConstants.RECHARGE);
                transactionHistory.setAmount(sysUserModel.getAmount());
                transactionHistory.setOptionUser(UserUtils.getUser().getPhone());
                transactionHistory.setRechargeUserPhone(sysUserModel.getPhone());
                transactionHistory.setSeparateFlag(0);
                int  i= sysUserMapper.updateUserAmountByPhone(sysUserModel);
                int j=transactionHistoryMapper.insert(transactionHistory);
                if(i>0&&j>0){
                    return CommonResult.ok(EmErrorCode.UPDATE_OK);
                }else{
                    return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
                }
            }else {
                return CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
        }catch (Exception e){
            return CommonResult.error(EmErrorCode.UPDATE_ERROR);
        }
    }

    /*
    * @Author 李中博
    * @Description 金币消费
    * @Date 2024/9/25 10:46
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param sysUserModel
    */
    @Override
    public synchronized CommonResult amountConsume(SysUserModel sysUserModel) throws CommonException {
        try {
            // 验证参数的规范性
            if(ObjectUtils.isNotEmpty(sysUserModel.getAmount())&&ObjectUtils.isNotEmpty(sysUserModel.getPhone())){
                BigDecimal zero = new BigDecimal(0.00);
                if(sysUserMapper.selectAmountByPhone(sysUserModel).getAmount().subtract(sysUserModel.getAmount()).compareTo(zero)>=0){
                    //消费记录
                    TransactionHistory transactionHistory=new TransactionHistory();
                    transactionHistory.setCreateTime(sysUserModel.getUpdateTime());
                    transactionHistory.setState(CommonConstants.CONSUME);
                    transactionHistory.setOptionUser(UserUtils.getUser().getPhone());
                    transactionHistory.setRechargeUserPhone(sysUserModel.getPhone());
                    transactionHistory.setSeparateFlag(0);
                    int  i= sysUserMapper.updateUserAmountByPhoneConsume(sysUserModel);
                    int  j=transactionHistoryMapper.insert(transactionHistory);
                    if(i>0&&j>0){
                        return CommonResult.ok(EmErrorCode.UPDATE_OK);
                    }else{
                        return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
                    }
                }else {
                    return CommonResult.error(EmErrorCode.BALANCE_IS_INSUFFICIENT);
                }
            }else {
                return CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
        }catch (Exception e){
            return CommonResult.error(EmErrorCode.UPDATE_ERROR);
        }
    }

    /*
    * @Author 李中博
    * @Description 查询用户信息并分页
    * @Date 2024/9/26 20:16
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param userName
    * @param pageRequest
    */
    @Override
    public CommonResult getUser(String userName, PageRequest pageRequest) throws CommonException{
        // 设置分页
        MybatisPageHelper.startPage(pageRequest);
        PageResult pageResult = MybatisPageHelper.getPageResult(sysUserMapper.selectSysUser(userName));
        return CommonResult.ok(pageResult);
    }

    /*
    * @Author 李中博
    * @Description 修改用户密码
    * @Date 2024/9/26 20:15
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param sysUserModel
    */
    @Override
    public CommonResult changePassword(SysUserModel sysUserModel) throws CommonException {
        SysUser sysUser=sysUserMapper.selectUserById(sysUserModel.getId());
        boolean matches = bCryptPasswordEncoder.matches(sysUserModel.getOldPassword(), sysUser.getPassword());
        if(matches){
            // 设置密码
            sysUser.setPassword(bCryptPasswordEncoder.encode(sysUserModel.getNewPassword()));
            int i = sysUserMapper.updateByPrimaryKeySelective(sysUser);
            if(i>0){
                return CommonResult.ok(EmErrorCode.UPDATE_OK);
            }else{
                return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
            }
        }else {
            return CommonResult.error(EmErrorCode.OLDPASSWORD_IS_NOT);
        }
    }



}
